package com.fastplatform.service;

import com.fastplatform.dto.UserInfo;
import com.fastplatform.entity.Role;
import com.fastplatform.entity.User;
import com.fastplatform.entity.UserRole;
import com.fastplatform.repository.RoleRepository;
import com.fastplatform.repository.UserRepository;
import com.fastplatform.repository.UserRoleRepository;
import com.fastplatform.specification.UserSpecification;

import org.mindrot.jbcrypt.BCrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private RoleRepository roleRepository;

    @Autowired
    private UserRoleRepository userRoleRepository;

    @Cacheable(value = "userInfo", key = "#userId")
    public UserInfo getUserInfo(Long userId) {
        Optional<User> userOpt = userRepository.findById(userId);
        if (userOpt.isEmpty()) {
            throw new RuntimeException("用户不存在");
        }

        User user = userOpt.get();
        UserInfo userInfo = new UserInfo();

        // 基本信息
        userInfo.setId(user.getId());
        userInfo.setUsername(user.getUsername());
        userInfo.setNickname(user.getNickname());
        userInfo.setEmail(user.getEmail());
        userInfo.setPhone(user.getPhone());
        userInfo.setAvatar(user.getAvatar());
        userInfo.setStatus(user.getStatus());
        userInfo.setUserType(user.getUserType());
        userInfo.setLastLoginTime(user.getLastLoginTime());
        userInfo.setLastLoginIp(user.getLastLoginIp());

        // 角色信息 - 优化查询，避免N+1问题
        List<UserRole> userRoles = userRoleRepository.findByUserIdAndDeletedFalse(userId);
        List<String> roleNames = new ArrayList<>();
        
        if (!userRoles.isEmpty()) {
            List<Long> roleIds = userRoles.stream()
                .map(UserRole::getRoleId)
                .toList();
            
            List<Role> roles = roleRepository.findByIdInAndDeletedFalse(roleIds);
            roleNames = roles.stream()
                .map(Role::getRoleName)
                .toList();
        }

        userInfo.setRoles(roleNames);
        userInfo.setPermissions(new ArrayList<>()); // 暂时为空，后续可扩展权限系统

        return userInfo;
    }

    /**
     * 获取所有用户（使用JPA命名推断）
     */
    public List<User> getAllUsers() {
        return userRepository.findByDeletedFalseOrderByCreateTimeDesc();
    }

    /**
     * 根据条件获取用户列表（使用JPA Criteria Queries）
     */
    public List<User> getUserList(String username, String phone, Integer status, String userType, Integer page, Integer size) {
        return userRepository.findAll(UserSpecification.findUsersByConditions(username, phone, status, userType));
    }
    @Transactional
    public User createUser(User user) {
        if (userRepository.existsByUsernameAndDeletedFalse(user.getUsername())) {
            throw new RuntimeException("用户名已存在");
        }
        user.setPassword(BCrypt.hashpw(user.getPassword(), BCrypt.gensalt()));
        return userRepository.save(user);
    }

    @Transactional
    @CacheEvict(value = "userInfo", key = "#user.id")
    public User updateUser(User user) {
        Optional<User> existingUserOpt = userRepository.findById(user.getId());
        if (existingUserOpt.isEmpty()) {
            throw new RuntimeException("用户不存在");
        }
        User existingUser = existingUserOpt.get();
        existingUser.setNickname(user.getNickname());
        existingUser.setEmail(user.getEmail());
        existingUser.setPhone(user.getPhone());
        existingUser.setAvatar(user.getAvatar());
        existingUser.setStatus(user.getStatus());
        if (user.getPassword() != null && !user.getPassword().trim().isEmpty()) {
            existingUser.setPassword(BCrypt.hashpw(user.getPassword(), BCrypt.gensalt()));
        }
        return userRepository.save(existingUser);
    }

    @Transactional
    public void deleteUser(Long userId) {
        Optional<User> userOpt = userRepository.findById(userId);
        if (userOpt.isPresent()) {
            User user = userOpt.get();
            user.setDeleted(true);
            userRepository.save(user);
        }
    }
    
    /**
     * 获取用户的角色ID列表
     */
    public List<Long> getUserRoles(Long userId) {
        List<UserRole> userRoles = userRoleRepository.findByUserIdAndDeletedFalse(userId);
        List<Long> roleIds = new ArrayList<>();
        for (UserRole userRole : userRoles) {
            roleIds.add(userRole.getRoleId());
        }
        return roleIds;
    }
    
    /**
     * 分配用户角色
     */
    @Transactional
    public void assignUserRoles(Long userId, List<Long> roleIds) {
        // 先删除用户原有的角色关联
        List<UserRole> existingUserRoles = userRoleRepository.findByUserIdAndDeletedFalse(userId);
        for (UserRole userRole : existingUserRoles) {
            userRole.setDeleted(true);
            userRoleRepository.save(userRole);
        }
        
        // 添加新的角色关联
        if (roleIds != null && !roleIds.isEmpty()) {
            for (Long roleId : roleIds) {
                // 过滤掉null值
                if (roleId != null) {
                    UserRole userRole = new UserRole();
                    userRole.setUserId(userId);
                    userRole.setRoleId(roleId);
                    userRoleRepository.save(userRole);
                }
            }
        }
    }
}